<template>
  <div class="app-container release" style="display: flex; justify-content: center; padding: 40px; padding-left: 0px; padding-right: 140px;padding-top: 50px">
    <el-form :model="form" ref="form" label-width="230px" :rules="rules" style="width: 60%">

      <el-form-item label="考试员工：" prop="userQywxIds" required>
        <dataTree
          class="tree-border"
          :data="form.userQywxIds"
          show-checkbox
          :default-expand-all="false"
          ref="empTree"
          node-key="id"
          :filter-node-method="filterNode"
          empty-text="加载中，请稍候"
          :props="defaultProps"
          @check-change="getTreeCheckedKeys"
          @node-click="handleNodeClick"
          :default-expanded-keys="treeExpandData"
          highlight-current
        />
      </el-form-item>
      <el-form-item label="是否企业微信通知：" prop="notice" required>
        <el-radio-group v-model="form.notice">
          <el-radio  v-for="item in noticeList"  :key="item.key"  :label="item.key" :value="item.key">{{item.value}}</el-radio>
        </el-radio-group>
      </el-form-item>


      <el-form-item style="margin-top: 60px; display: flex; justify-content: center;">
        <el-button plain @click="$router.push('/task/list')" style="margin-right: 10px">取消</el-button>
        <el-button type="success" @click="resetForm" style="margin-right: 12px;">重置</el-button>
        <el-button type="primary" @click="submitForm" style="margin-right: 38px">提交</el-button>
      </el-form-item>
    </el-form>

  </div>
</template>

<script>
import QuestionShow from '../exam/question/components/Show'
import Ueditor from '@/components/Ueditor'
import { mapGetters, mapState, mapActions } from 'vuex'
import taskApi from '@/api/task'
import paperApi from '@/api/examPaper'
import userApi from '@/api/user'
import dataTree from '@/components/tree/src/tree.vue'

export default {
  components: {
    Ueditor, QuestionShow, dataTree
  },
  data () {
    return {
      treeExpandData: [],
      activated: false,
      autocompleteFlag: false,
      paperTp: [
        { id: 1, name: '固定考试' },
        { id: 4, name: '时段考试' }
      ],
      empOptions: [],
      defaultProps: {
        children: 'children',
        label: 'label'
      },
      filterText: '',
      form: {
        examId:undefined,
        name: '',
        category: '',
        paperId: undefined,
        userQywxIds: [],
        notice: true,
        repetition: false,
        limitCount: 0,
        credit: 1
      },
      empList: [],
      categoryList: [],
      paperList: [],
      noticeList: [
        { key: true, value: '是' },
        { key: false, value: '否' }
      ],
      repeatList: [
        { key: true, value: '是' },
        { key: false, value: '否' }
      ],
      subjectFilter: null,
      formLoading: false,
      rules: {
        name: [
          { required: true, message: '请输入考试标题', trigger: 'change' }
        ],
        category: [
          { required: true, message: '请选择（或输入）考试分类', trigger: 'change' }
        ],
        paperId: [
          { required: true, message: '请输入关联试卷名称', trigger: 'blur' }
        ],
        userQywxIds: [
          { required: true, message: '请选择（或输入）考试员工', trigger: 'blur' }
        ],
        notice: [
          { required: true, message: '请选择是否开启企业微信提醒', trigger: 'blur' }
        ],
      },
      richEditor: {
        dialogVisible: false,
        object: null,
        parameterName: '',
        instance: null
      },
      questionShow: {
        qType: 0,
        dialog: false,
        question: null,
        loading: false
      },
      parentList: [],
      searchData: {}
    }
  },
  created () {
    let exId = this.$route.query.examId
    if (this.$route.query.jump) {
      if (exId != null &&
      exId != undefined &&
      exId!= '') {
        this.$set(this.form, 'examId', parseInt(exId))
      }
    }
    this.loadAll()
  },
  watch: {
    filterText(val) {
      this.$refs.empTree.filter(val);
    },
    'form.category': {
      handler(newName, oldName) {
        if (newName == '') {
          // alert('ddd')
          // this.searchHandle()
        }
      },
      immediate: true,
      deep: true
    }
  },
  methods: {
    getRoleTreeRootNode(res) {
      this.treeExpandData.push(res[0].id)
    },
    handleFocus(event) {
      this.activated = true;
      this.$emit('focus', event);
      // if (this.triggerOnFocus) {
      //   this.debouncedGetData(this.value);
      // }
    },
    handleBlur(event) {
      this.$emit('blur', event);
    },
    searchHandle() {
      if(this.autocompleteFocusFlag) this.$refs.autocomplete.activated = true;
      this.querySearch0()
    },
    // 清除的方法
    handleClear() {
      this.activated = false;
      this.$emit('clear');
    },
    handleNodeClick(item, node) {
      console.log('item: ',item,'data: ', node);
      this.parentList = [];
      this.getParent(node);
    },
    // 根据当前获取的tree节点信息查找父节点
    getParent (node) {
      if(node.isLeaf == false && node.parent.parent == null){ //
          this.parentList.push(node.data);
      }else{
          if(node.isLeaf == false && node.parent.parent != null ){ //
            this.parentList.push(node.data);
            this.getParent(node.parent)
          }else if(node.isLeaf == true && node.parent.parent != null){
              this.parentList.push(node.data);
              this.getParent(node.parent)
          }
      }
    },
    // 共三个参数，依次为：1. 传递给 data 属性的数组中该节点所对应的对象、2. 节点本身是否被选中、3. 节点的子树中是否有被选中的节点
    getTreeCheckedKeys(data, checked) {
      let arr = this.$refs.empTree.getCheckedKeys()
      let newarr = []
      this.$refs.empTree.setCheckedKeys([])
      arr.forEach((item,index) => {
        if (typeof item ==  'string') {
          newarr.push(item)
          this.$refs.empTree.setChecked(item, true, false)
        } else{
          this.$refs.empTree.setChecked(item, false, false)
        }
      })
      // this.$refs.empTree.setCheckedKeys(newarr)
    },
    // 所有菜单节点数据
    getMenuAllCheckedKeys() {
      // 目前被选中的菜单节点
      let checkedKeys = this.$refs.empTree.getCheckedKeys()
      // 半选中的菜单节点
      let halfCheckedKeys = this.$refs.empTree.getHalfCheckedKeys()
      checkedKeys.unshift.apply(checkedKeys, halfCheckedKeys)
      return checkedKeys
    },
    filterNode(value, data) {
      if (!value) return true;
      return data.label.indexOf(value) !== -1;
    },
    resetForm() {
     this.form = {
        name: '',
        category: '',
        paperId: undefined,
        userQywxIds: [],
        notice: true,
        repetition: false,
        limitCount: 0,
        credit: 1
      }
      this.$refs.empTree.setCheckedKeys([])
      this.findZNodes()
    },
    loadAll() {
      taskApi.getTaskCategorys().then(res => {
        const categoryList = res.response
        this.categoryList = categoryList
      })

      paperApi.pageList().then(res => {
        this.paperList = res.response.list
      })

      this.findZNodes()
    },
    /** 转换项目数据结构 */
    normalizer(node) {
      if (node.children && !node.children.length) {
        delete node.children;
      }
      return {
        id: node.id,
        label: node.label,
        children: node.children
      };
    },
    //加载修改树结构json
    findZNodes() {
      userApi.getUserDepartsTree().then(res => {
        const mapTree = org => {
            const haveChildren = Array.isArray(org.children) && org.children.length > 0
            let newId
            // if (org.children.length  == 0) {
            if (org.type == 2) {
              let pLen =  (org.parentid).toString().length
              let zeroCount = 5 - pLen
              let zeroStr = '',
              zero = '0'
              let i
              for (i = 0;i < zeroCount; i++) {
                zeroStr += zero
              }
              newId = org.parentid + zeroStr + org.id
              // console.log('newid:', newId)
            }

            // id : org.children.length  > 0 ? org.id : newId,
            return {
                type: org.type,
                id: org.type == 1 ? org.id : newId,
                label: org.label,
                parentid: org.parentid,
                children:haveChildren ? org.children.map(i => mapTree(i)) : [],
            }
        };
        let treeNewData = res.response.map(org => mapTree(org) )
        console.log('newTree:', treeNewData)
        // this.form.userQywxIds = res.response
        this.form.userQywxIds = treeNewData

        this.getRoleTreeRootNode(res.response)
      })
    },
    fuzzyqueryJob(e, input) {
      if (this.form.category !== '' && this.form.category !== null && this.form.category !== undefined) {
        const jobParam = { keyword: this.form.category + '' }
        taskApi.getTaskCategorys(jobParam).then(res => {
          this.categoryList = res.response
        })
        this.input = e.target.value
      }
    },
    fuzzyqueryJob2(e, input) {
      if (this.form.paperId !== '' && this.form.paperId !== null && this.form.paperId !== undefined) {
        const jobParam = { nameKeyword: this.form.paperId + '' }
        paperApi.pageList(jobParam).then(res => {

          if (res.response.list.length > 0) {
            this.paperList = []
            res.response.list.forEach(item => {
              this.paperList.push({key: item.id, value: item.name })
            });
          }
          const joblist = this.paperList
          result = joblist.map(item => {
            return item.value
          })
          this.paperList = result
        })
        this.input = e.target.value
      }
    },
    createFilter(queryString) {
      return returnJobs => {
        return (
          returnJobs.toLowerCase().indexOf(queryString.toLowerCase()) !== -1 // 改为===0 就是筛选的数据只是首字匹配的列表项，需要包含输入字的所有列表项改为！==-1
        )
      }
    },
    querySearch0(queryString, cb) {
      const categorylist = this.categoryList
      let results = queryString
        ? categorylist.filter(this.createFilter(queryString))
        : categorylist
      results = results.map(item => {
        return {
          value: item
        }
      })
      cb(results)
    },
    querySearch2(queryString, cb) {
      const paperlist = this.paperList
      let results = queryString
        ? paperlist.filter(this.createFilter(queryString))
        : paperlist
      results = results.map(item => {
        return {
          value: item
        }
      })
      cb(results)
    },
    RndNum(n) {
      // 生成随机数
      let rdmNum = ''
      for (let i = 0; i < n; i++) {
        rdmNum += Math.floor(Math.random() * 10) // [0,10)的整数
      }
      return rdmNum
    },
    editorReady (instance) {
      this.richEditor.instance = instance
      let currentContent = this.richEditor.object[this.richEditor.parameterName]
      this.richEditor.instance.setContent(currentContent)
      // 光标定位到Ueditor
      this.richEditor.instance.focus(true)
    },
    inputClick (object, parameterName) {
      this.richEditor.object = object
      this.richEditor.parameterName = parameterName
      this.richEditor.dialogVisible = true
    },
    editorConfirm () {
      let content = this.richEditor.instance.getContent()
      this.richEditor.object[this.richEditor.parameterName] = content
      this.richEditor.dialogVisible = false
    },
    questionItemRemove (index) {
      this.form.items.splice(index, 1)
    },
    questionItemAdd () {
      let items = this.form.items
      let newLastPrefix
      if (items.length > 0) {
        let last = items[items.length - 1]
        newLastPrefix = String.fromCharCode(last.prefix.charCodeAt() + 1)
      } else {
        newLastPrefix = 'A'
      }
      items.push({ id: null, prefix: newLastPrefix, content: '' })
    },
    unique(arr) {
      var x = new Set(arr);
      let a = [...x]
      return [...x]
    },
    submitForm () {
      let _this = this
      this.$refs.form.validate((valid) => {
        if (valid) {
          if (_this.$refs.empTree.getCheckedKeys().length == 0) {
            _this.$message.error('请勾选考试员工')
            _this.formLoading = false
            return
          }
          this.formLoading = true

          const selectedKeysArr = this.$refs.empTree.getCheckedKeys()
          let newArr = []
          selectedKeysArr.forEach(item => {
            if (typeof item == 'string') {
              newArr.push(item.slice(5))
            }
          })
          // console.log('newArr:', newArr)
          // this.form.userQywxIds  = this.$refs.empTree.getCheckedKeys()
          this.form.userQywxIds  = newArr
          taskApi.addExamPerson(this.form).then(re => {
            console.log('res:', re)
            if (re.code === 1) {
              _this.$message({
                type: 'success',
                message: this.form.name + '追加考试人员成功!'
              })
              this.loadAll()
              this.$refs.empTree.setCheckedKeys([])
              this.resetForm()
              _this.delCurrentView(_this).then(() => {
                _this.$router.push('/task/list')
              })
            } else {
              this.$message({
                type: 'warning',
                message: re.message
              })
              this.formLoading = false
              this.loadAll()
              this.$refs.empTree.setCheckedKeys([])
              this.resetForm()
              _this.findZNodes()
            }
          }).catch(error => {
            _this.$message({
              type: 'warning',
              message: re.message
            })
            _this.formLoading = false
            _this.loadAll()
            _this.$refs.empTree.setCheckedKeys([])
            _this.resetForm()
            _this.findZNodes()
          }).finally(() => {
            this.formLoading = false
            this.loadAll()
            this.$refs.empTree.setCheckedKeys([])
            this.resetForm()
            _this.findZNodes()
          })
        } else {
          return false
        }
      })
    },
    ...mapActions('exam', { initSubject: 'initSubject' }),
    ...mapActions('tagsView', { delCurrentView: 'delCurrentView' })
  },
  computed: {
    ...mapGetters('enumItem', ['enumFormat']),
    ...mapState('enumItem', {
      questionTypeEnum: state => state.exam.question.typeEnum,
      examTypeEnum: state => state.exam.examPaper.examTypeEnum,
      levelEnum: state => state.user.levelEnum
    }),
    ...mapState('exam', { subjects: state => state.subjects })
  }
}
</script>

<style rel="stylesheet/scss" lang='scss'>
.release .el-autocomplete {
  position: relative;
  display: inline-block;
  width: 100%;
}

.release .el-select {
  display: inline-block;
  position: relative;
  width: 100%;
}

.release .el-form-item__error {
  color: #ff4949;
  font-size: 12px;
  line-height: 1;
  padding-top: 0px;
  position: absolute;
  top: 100%;
  left: 0;
}

</style>
